package com.atfunny.LibraryMS.service;

import com.atfunny.LibraryMS.javabean.Book;
import com.atfunny.LibraryMS.view.LMSUtility;

/**
 * @ClassName BookList
 * @Description 用于储存 Book 类
 * @Author AqFunny
 * @Date 2021/10/4 16:47
 * @Version 1.0
 */
public class BookList {
    private int bookNumber = 0;
    private static final int bookMaxSize = 10;
    private static int publisherCode = 2417;            //出版社代码
    private static int bookSequenceCode = 1001;         //书序码

    private Book[] bookList = new Book[bookMaxSize];    //开辟一个容量为 bookMaxSize 的数组空间

//    public BookList() throws BookException {
//        addBook(new Book("白夜行", "东野圭吾", "南海出版公司", "2区66行A面3排", "free"));
//    }

    /**
    * @Description 添加书籍
    * @Date 17:29 2021/10/4
    * @Param [book]
    * @return void
    **/
    protected void addBook(Book book) throws BookException{
        if(bookNumber >= bookMaxSize) {
            throw new BookException("馆藏书籍已满，无法继续添加！");
        }
        book.setISBNCode("978-7-" + publisherCode++ + "-" + bookSequenceCode++ + "-" + ((int)(Math.random()*9)+1));
        bookList[bookNumber++] = book;
    }
    /**
    * @Description 通过 ISBN 码对书籍进行删除操作
    * @Date 17:52 2021/10/4
    * @Param [ISBN]
    * @return void
    **/
    public void deleteBook(String ISBN) throws BookException{
        if(bookNumber == 0) {
            throw new BookException("馆中目前不存在任何书籍");
        }
        boolean isExist = false;
        for (int i = 0; i < bookNumber; i++) {
            if(bookList[i].getISBNCode().equals(ISBN)) {
                System.out.print("是否确认删除《" + bookList[i].getName() + "》(Y/N)");
                char confirm = LMSUtility.readConfirmSelection();
                if(confirm == 'N') {
                    break;
                }
                for (int j = i; j < bookNumber-1; j++) {
                    bookList[j] = bookList[j+1];
                }
                bookList[--bookNumber] = null;
                System.out.println("删除成功");
                isExist = true;
                break;
            }
        }
        if(!isExist) {
            throw new BookException("ISBN码为 \"" + ISBN + "\" 的书籍不存在，无法删除");
        }
    }

    public int getBookNumber() {
        return bookNumber;
    }

    public Book[] getBookList() {
        return bookList;
    }
}
